package com.weme.mine.activity

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.updateLayoutParams
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.example.resources.R
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.makeramen.roundedimageview.RoundedImageView
import com.weme.common.activity.LookBigImgActivity
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.dialog.*
import com.weme.common.manager.SocketConnectManager.errorService
import com.weme.common.network.FollowBean
import com.weme.common.util.*
import com.weme.common.view.BottomSelectionDialog
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.CustomTopNavigationBarListener
import com.weme.common.view.SelectionItem
import com.weme.mine.databinding.ActivityUserInfoBinding
import com.weme.mine.fragment.UserInfoImgFragment
import com.weme.mine.viewmode.UserInfoViewMode
import dev.kratos.api.user_server.v1.*
import io.agora.chat.ChatClient


@Route(path = ARouterPaths.MINE_USER_INFO_ACTIVITY)
class UserInfoActivity : BaseMvvmActivity<ActivityUserInfoBinding, UserInfoViewMode>(), BottomSelectionListener {
    val items by lazy {
        mutableListOf<Media>()
    }
    val giftList by lazy {
        mutableListOf<GiftWall>()
    }

    var lastHead = ""

    var user: Users? = null

    var isMy = false
    var albumBean = ""
    var alertDialog: AlertDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.customTopNavigationBar).init()

        val receivedBundle = intent.extras //这里崩了还玩个锤子
        viewModel.userId = receivedBundle?.getLong(ARouterHelper.KEY_USER_ID, 0L) ?: UserMKHelper.decodeLong(UserMKHelper.UID)
        isMy = viewModel.userId == UserMKHelper.decodeLong(UserMKHelper.UID)
        mBinding.imGift.setVisible(!isMy)
        mBinding.viewUserInfoYouModified.setVisible(!isMy)
        mBinding.viewUserInfoMeModified.setVisible(isMy)

        observeViewModel()
        mBinding.customTopNavigationBar.listener = object : CustomTopNavigationBarListener {
            override fun onMoreButtonClicked() {
                DialogUtils.createAndShowBottomSelectionDialog(this@UserInfoActivity, "Dialog Title", this@UserInfoActivity)
            }
        }
        if (isMy) { //
            val params = mBinding.magical.layoutParams as ConstraintLayout.LayoutParams
            params.topToBottom = mBinding.vp2.id
            params.bottomToBottom = ConstraintLayout.LayoutParams.UNSET
            params.topMargin = resources.getDimensionPixelSize(R.dimen.dp_6)
            params.bottomMargin = resources.getDimensionPixelSize(R.dimen.dp_0)
            mBinding.magical.layoutParams = params
            mBinding.imGifts.gone()
            mBinding.tvGift.gone()
            mBinding.rcvList.gone()
            mBinding.imChat.gone()
            mBinding.calCall.gone()
            mBinding.imGift.gone()
            mBinding.customTopNavigationBar.post {
                mBinding.customTopNavigationBar.setTitle(getString(R.string.user_preview_title))
//                val params = mBinding.nsvView.layoutParams as ViewGroup.MarginLayoutParams
//                params.topMargin = dp2px(96)
//                mBinding.nsvView.layoutParams = params
                mBinding.nsvView.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                    this.topMargin = dp2px(96)
                }
                mBinding.nsvView.requestLayout()
                mBinding.customTopNavigationBar.getMore().visible()
                mBinding.customTopNavigationBar.getMore().setImageResource(R.drawable.icon_user_more)
                mBinding.customTopNavigationBar.listener = object : CustomTopNavigationBarListener {
                    override fun onMoreButtonClicked() {
                        ARouterHelper.navigateToActivityWithResult(this@UserInfoActivity, ARouterPaths.MINE_ED_USERINFO_ACTIVITY, 100)
                    }
                }
            }


//            mBinding.nsvView.setOnScrollChangeListener(object : View.OnScrollChangeListener {
//                override fun onScrollChange(v: View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
//                    Log.e("Scroll", "scrollY =" + scrollY + "oldScrollY=" + oldScrollY)
//                    val maxScroll = 300 // 最大滚动距离，透明度达到50%
//                    val alpha = Math.min(1f, scrollY / maxScroll.toFloat())
//
//                    // 将透明度范围从0到50（即ARGB alpha范围从0到127.5）
//                    val alphaValue = (alpha * 127.5).toInt()
//
//                    // 设置透明度
//                    mBinding.customTopNavigationBar.setBackgroundColor(Color.argb(alphaValue, 255, 255, 255))
//                }
//
//            })
        } else {
            mBinding.imGifts.visible()
            mBinding.tvGift.visible()
            mBinding.customTopNavigationBar.getMore().visible()
            mBinding.customTopNavigationBar.getMore().setImageResource(R.mipmap.icon_chat_more)
            mBinding.customTopNavigationBar.listener = object : CustomTopNavigationBarListener {
                override fun onMoreButtonClicked() {
                    val selectionItems = listOf(
                        SelectionItem(getString(R.string.report), 0, object : BottomSelectionListener {
                            override fun onTitleClicked(position: Int) {
                                val reportList = listOf(SelectionItem(getString(R.string.report_1), 0, this@UserInfoActivity), SelectionItem(getString(R.string.report_2), 1, this@UserInfoActivity), SelectionItem(getString(R.string.report_3), 2, this@UserInfoActivity), SelectionItem(getString(R.string.report_4), 3, this@UserInfoActivity), SelectionItem(getString(R.string.report_5), 4, this@UserInfoActivity), SelectionItem(getString(R.string.report_6), 5, this@UserInfoActivity), SelectionItem(getString(R.string.report_7), 6, this@UserInfoActivity))
                                val reportDiaolg = BottomSelectionDialog.newInstance(reportList)
                                reportDiaolg.show(this@UserInfoActivity.supportFragmentManager,"BottomSelectionDialog")
                                reportDiaolg.setTitle(getString(R.string.report))
                            }

                        }),
                        SelectionItem(getString(R.string.block), 1, object : BottomSelectionListener {
                            override fun onTitleClicked(position: Int) {
                                viewModel.setBlock(BlackRequest.newBuilder().setBlackUid(viewModel.userId).build())
                                if (alertDialog == null) {
                                    alertDialog = createProgressDialog()
                                }
                                alertDialog?.show()
                            }

                        }),
                    )
                    val btndialog = BottomSelectionDialog.newInstance(selectionItems)
                    btndialog.show(this@UserInfoActivity.supportFragmentManager,"")
                }
            }
            mBinding.viewUserInfoYouModified.setInitView(this)
            viewModel.getMseeageList(GetUserInfoRequest.newBuilder().addUids(viewModel.userId).build())
            viewModel.getAlubm(GetAlbumRequest.newBuilder().setUid(viewModel.userId).build()) //            viewModel.getGiftList()
            giftAdapter.submitList(giftList)
            mBinding.rcvList.adapter = giftAdapter


        }

        initClick()
        Log.e("tag", viewModel.userId.toString())
     LiveEventBus.get<Any>(LiveConfig.NET_WORK_USER_IFNO).observe(this) {
            if (it is FollowBean) {
                if (it.isFollow) {
                    showToast(getString(R.string.toast_success))
                }
                viewModel.isFollow = it.isFollow
                mBinding.viewUserInfoYouModified.setFollow()
            } else if (it is Users) {
                initInitView(it)
            } else if (it is GetAlbumReply) {
                try {
                    if (albumBean == gson.toJson(it)) {
                        return@observe
                    }
                    items.clear()
                    if (it.mediaList.isEmpty()) {
                        val media1 = Media.newBuilder().setType(1).setUrl("").build()
                        items.add(media1)
                    } else {
                        val sortedMediaList = it.mediaList.sortedByDescending { !it.type.isTypeImg() }
                        items.addAll(sortedMediaList)
                    }
                    albumBean = gson.toJson(it)
                    initViewPage()
                } catch (_: Exception) {

                }
            } else if (it is SendGiftReply) {
                user?.apply {
                    if (TextUtils.isEmpty(it.gift.giftUrl)) {
                        val giftSendSuccessDialog = GiftSendSuccessDialog(this.nickname, this.headPic)
                        giftSendSuccessDialog.show(this@UserInfoActivity.supportFragmentManager, "GiftSendSuccessDialog")
                    } else {

                        mBinding.playerView.loadVideoFromAssets(it.gift.giftName+".mp4" , it.gift.md5) {
                            downloadMp4(it.gift.giftUrl, it.gift.giftName) { isDow ->
                                if (isDow == true) {
                                    mBinding.playerView.loadVideoFromAssets(it.gift.giftName + ".mp4", it.gift.md5) {

                                    }
                                }

                            }
                        }
                    }
                    lastHead =  UserMKHelper.decodeString(AppMkHelper.HEADPIC)
                    if (giftList.size == 0) {
                        it.gift.apply {
                            giftList.add(0, GiftWall.newBuilder().setGiftName(giftName).setGiftNum(1).setGiftUrl(giftIcon).build())
                        }
                    } else {
                        val position = giftList.indexOfFirst { gift ->
                            Log.e("gift", gift.giftUrl)
                            Log.e("gift", it.gift.giftUrl)
                            gift.giftName == it.gift.giftName
                        }
                        if (position == -1) { //代表没有收到过这个礼物
                            it.gift.apply {
                                giftList.add(0, GiftWall.newBuilder().setGiftName(giftName).setGiftNum(1).setGiftUrl(giftIcon).build())
                            }
                        } else {
                            if (position != 0) {
                                val giftToMove = giftList.removeAt(position)
                                giftList.add(0, giftToMove)
                            }
                            giftList[0].apply {
                                giftList[0] = GiftWall.newBuilder().setGiftName(giftName).setGiftNum(giftNum + 1).setGiftUrl(giftUrl).build()
                            }
                        }

                    }
                    giftAdapter.notifyDataSetChanged()
                    AgoraClient.sendImGiftMsg(this.uid.toString(), it.gift)

                }


            } else if (it is GetGiftWallReply) {
                giftList.clear()
                lastHead =  UserMKHelper.decodeString(AppMkHelper.HEADPIC)
                giftList.addAll(it.giftWallList)
                giftAdapter.notifyDataSetChanged()

            }
        }





     LiveEventBus.get<Any>(LiveConfig.NET_WORK_CHAT).observe(this) {
            if (it is BlackReply) {
                ChatClient.getInstance().chatManager().deleteConversation(viewModel.userId.toString(), true)
                showToast(getString(com.example.resources.R.string.block_bolck_tip, user!!.nickname))

                UtilsApp.getActivityList().forEach {
                    if (it.get()!!.localClassName == "ChatActivity") {
                        it.get()!!.finish()
                    }
                }
                finish()
            } else if (it is UnBlackReply) { //  ChatClient.getInstance().contactManager().getBlackListUsernames()
            } else if (it is ReportReply) { //举报回调
                showToast(getString(R.string.report_successful))
            }
        }
        errorService.observe(this) {
            alertDialog?.hide()
        }

        // 设置 View 的布局完成监听器来测量实际高度
        checkAndSetupScrollGradient()

    }
    private fun checkAndSetupScrollGradient() {
        mBinding.nsvView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                // 获取实际高度
                val viewHeight = mBinding.nsvView.getChildAt(0).height
                val scrollViewHeight = mBinding.nsvView.height

                // 计算最大可滚动距离
                val maxScroll = (viewHeight - scrollViewHeight).coerceAtLeast(0)

                if (maxScroll > 0) {
                    // 调用滚动渐变方法
                    setupScrollGradient(maxScroll)
                    // 移除监听器，防止重复调用
                    mBinding.nsvView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                } else {
                    // 递归调用，直到 maxScroll > 0
                    mBinding.nsvView.post {
                        checkAndSetupScrollGradient()
                    }
                }
            }
        })
    }
    private fun setupScrollGradient( maxScroll: Int) {

        mBinding.nsvView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            Log.e("tag","maxScroll"+maxScroll.toString())
            Log.e("tag","scrollY"+scrollY.toString())
            // 计算透明度比例：顶部 0 到底部 0.5
            val alpha = (scrollY.toFloat() / maxScroll).coerceIn(0f, 1f) * 0.5f
            // 将透明度应用于颜色
            val backgroundColor = Color.argb((alpha * 255).toInt(), 0, 0, 0)
            // 设置背景颜色
            mBinding.customTopNavigationBar.setBackgroundColor(backgroundColor)
        })
    }

    override fun onResume() {
        super.onResume()
        if (isMy) {
            viewModel.getUserMeInfo(GetUserInfoRequest.newBuilder().build())
            viewModel.getAlubm(GetAlbumRequest.newBuilder().build())
        } else {
            viewModel.getGiftWall(viewModel.userId)
            mBinding.calCall.playSVGAFromAssets("video_preview_call_her")
            mBinding.svgaGift.playSVGAFromAssets("gift_button_animation")
        }
    }

    override fun onPause() {
        super.onPause()
        mBinding.svgaGift.stopAnimation()
        mBinding.calCall.stopAnimation()
    }

    override fun finish() {
        alertDialog?.dismiss()
        super.finish()
    }

    var giftDialog: GiftDialog? = null
    private fun initClick() {
        mBinding.imGift.setOnClickListener {
            if (null == giftDialog) {
                giftDialog = user?.let { it1 ->
                    GiftDialog(it1.nickname, object : GiftDialogCallback {
                        override fun sendGiftInfo(giftInfo: GiftInfo) {
                            viewModel.sendGift(SendGiftRequest.newBuilder().setGiftId(giftInfo.id).setGiftNum(1).setUid(viewModel.userId).build())
                            giftDialog?.dismiss()
                        }
                    })
                }
            }

            giftDialog?.show(this.supportFragmentManager, "")
        }

        mBinding.imChat.setOnFastClickListener {

            user?.let {
                ARouterHelper.navigateToChatActivity(this, it)
//                if(it.isBlack){
//                    showToast(getString(R.string.blocked_user_message, it.nickname))
//                    return@setOnFastClickListener
//                }
//                IsBlackInfoDialog.show(this.supportFragmentManager, it.uid.toString()) { isBlack->
//                    if (isBlack) {
//                        ARouterHelper.navigateToChatActivity(this, it)
//                    } else {
//                        showToast(getString(R.string.chat_block_you, it.nickname))
//                    }
//                }

            }
        }
        mBinding.calCall.setOnFastClickListener {

            user?.apply {
                viewModel.callsPhone(this)
//                if(isBlack){
//                    showToast(getString(R.string.blocked_user_message, this.nickname))
//                    return@setOnFastClickListener
//                }
//                IsBlackInfoDialog.show(this@UserInfoActivity.supportFragmentManager, this.uid.toString()) { isBlack->
//                    if (isBlack) {
//                        viewModel.callsPhone(this)
//                    } else {
//                        showToast(getString(R.string.chat_block_you, this.nickname))
//                    }
//                }

            } //            val intent = Intent(this, CallActivity::class.java)
            //            val options = ActivityOptions.makeCustomAnimation(this, com.weme.common.R.anim.fade_in, com.weme.common.R.anim.fade_out)
            //            startActivity(intent, options.toBundle())
        }

    }

    private fun initInitView(user: Users) {
        this.user = user
        if (!isMy) {
            viewModel.isFollow = user.isFollow == 1
            mBinding.viewUserInfoYouModified.setMode(user)
        } else {
            mBinding.viewUserInfoMeModified.setMode(user)
        } //  initViewPage()
    }

    private fun initViewPage() {
        val fragment = mutableListOf<Fragment>()
        items.forEach {
            val userInfoImgFragment = UserInfoImgFragment.newInstance(it.type, it.url, viewModel.userId == UserMKHelper.decodeLong(UserMKHelper.UID))
            fragment.add(userInfoImgFragment)
        }
        mBinding.vp2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return items.size
            }

            override fun createFragment(p0: Int): Fragment {
                return fragment[p0]
            }
        }

        mBinding.magical.attachViewPager(mBinding.vp2, items, isMy)
        if(isMy){
            if(items.size<=1){
                mBinding.magicalNew.gone()
            }else{
                mBinding.magicalNew.attachViewPager(mBinding.vp2, items.size)
            }

        }


    }

    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}


    override fun onDestroy() {
        mBinding.playerView.stopPlay()
        mBinding.playerView.release()

        mBinding.vp2.adapter = null
        mBinding.svgaGift.stopAnimation()
        mBinding.svgaGift.clear()
        mBinding.calCall.stopAnimation()
        mBinding.calCall.clear()

        Glide.get(this).clearMemory()
        super.onDestroy()
    }

    override fun getViewModelClass(): Class<UserInfoViewMode> = UserInfoViewMode::class.java

    private fun observeViewModel() {
        viewModel.clickBigImgLiveData.observe(this) {
            if (items.size != 0 && !TextUtils.isEmpty(items[0].url)) {
                val userBuilder = Users.newBuilder()
                user?.let { it1 ->
                    userBuilder.uid = it1.uid
                    userBuilder.nickname = it1.nickname
                    userBuilder.age = it1.age
                    userBuilder.setCountryCode(it1.countryCode)
                }

                userBuilder.addAllMedia(items)

                LookBigImgActivity.openActivity(this@UserInfoActivity, userBuilder.build(), mBinding.vp2.currentItem, resultLauncher)

            }

        }

    }


    private val giftAdapter = object : BaseQuickAdapter<GiftWall, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: GiftWall?) {
            item?.apply {
                holder.getView<ImageView>(com.weme.mine.R.id.imGift).loadImage(this.giftUrl)
                holder.setText(com.weme.mine.R.id.tvGift, "x" + this.giftNum)
                val calUser = holder.getView<ConstraintLayout>(com.weme.common.R.id.calUser)
                calUser.setVisible(holder.absoluteAdapterPosition == 0)
                if (holder.absoluteAdapterPosition == 0) {
                    holder.getView<RoundedImageView>(com.weme.mine.R.id.imHead).loadImage(lastHead)

                }

            }


        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(com.weme.common.R.layout.item_user_gift, parent)
        }


    }

    override fun onTitleClicked(position: Int) {
        when (position) {
            0 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_1)).build())
            }
            1 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_2)).build())
            }
            2 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_3)).build())
            }
            3 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_4)).build())
            }
            4 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_5)).build())
            }
            5 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_6)).build())
            }
            6 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(user!!.uid).setReportContent(getString(R.string.report_7)).build())
            }
        }
    }
}